--
-- @Author:      name
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 消息的处理
local skynet = require "skynet"
local redis = require "skynet.db.redis"
local server_config = dofile(skynet.getenv("server_config"))

local table_remove = table.remove
local table_insert = table.insert


local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor(message_dispatch)

	self.message_dispatch = message_dispatch
	self.disconnected = false
	
	local db_conf = server_config.db_conf	
	self.host = db_conf.redis.ip
	self.port = db_conf.redis.port
	self.auth = db_conf.redis.auth
	self.db_id = 0	

	self.db_info = {
		host = self.host,
		port = self.port,
		db = self.db_id,
		auth = self.auth,
	}
	self.connections = {} --连接池
	self.allocated_connection_num = 0
	self.max_connection_num = 100 

	self:register()
end

--注册本服务里的消息
function MessageHandler:register()
	self.message_dispatch:registerSelf("start", handler(self,self.start))
    self.message_dispatch:registerSelf('hotfix', handler(self, self.hotfixFile))
	self.message_dispatch:registerSelf("redis_cmd", handler(self,self.redisCommand))
end

--热更文件
function MessageHandler:hotfixFile(file_name)
    dbglog("____hotfix_____", file_name)
    return global.hotfix:hotfixFile(file_name)
    
end

--从连接池里取一个服务
function MessageHandler:getConnect()
    local connections = self.connections
    if #connections > 0 then
        return table_remove(connections)
    end
    while self.allocated_connection_num >= self.max_connection_num do
        --超上限了，唯有空转等了
        -- dbglog('there is no redis connection,  waiting')
        skynet.sleep(5)
        if #connections > 0 then
            return table_remove(connections)
        end
    end

    local redis_conf = self.db_info
    local ok, ret = xpcall(redis.connect, debug.traceback, redis_conf)
    while not ok do
        errlog('failed to connect redis',ret, redis_conf)
        skynet.sleep(150)   --one second
        ok, ret = xpcall(redis.connect, debug.traceback, redis_conf)
    end

    self.allocated_connection_num = self.allocated_connection_num + 1
    return ret
end



---------------------------------------------------------
-- CMD
---------------------------------------------------------

function MessageHandler:start()

	return true
end


--redis命令处理
function MessageHandler:redisCommand(cmd, ...)
	local db = self:getConnect()	
	local func = db[cmd]
    local ok,ret = xpcall(func, debug.traceback, db, ...)
    while not ok do
        errlog("___发送消息给redis错误___", ret)
        skynet.sleep(100)
        print('now retry....')
        ok,ret = xpcall(func, debug.traceback, db, ...)
    end
    --把连接放回池中
	table_insert(self.connections, db)

	return ret
end










return MessageHandler